package org.hugh.trade.mq;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.hugh.trade.common.EntrustStatusEnum;
import org.hugh.trade.common.MConstants;
import org.hugh.trade.model.EntrustOrder;
import org.hugh.trade.model.EntrustRequest;
import org.hugh.trade.service.impl.MatchEngineImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 监听委托订单topic
 */

@Service
@RocketMQMessageListener(topic = "order", consumerGroup = "trade-match")
public class TradeOrderListener implements RocketMQListener<EntrustRequest> {

    private static final Logger log = LoggerFactory.getLogger(TradeOrderListener.class);

    @Autowired
    private MatchEngineImpl matchEngine;

    @Override
    public void onMessage(EntrustRequest request) {
        log.info("receive Order {}", request);
        matchEngine.placeOrder(convert2Order(request));
    }

    EntrustOrder convert2Order(EntrustRequest request) {
        EntrustOrder order = new EntrustOrder();
        // todo 全局唯一自增ID
//        order.setEntrustId();
        order.setAccountId(request.getAccountId());
        order.setDirect(request.getDirect());
        order.setSecCode(request.getSecCode());
        order.setEntrustQty(request.getEntrustQty());
        order.setPrice(request.getPrice());
        order.setTimestamp(System.currentTimeMillis());

        order.setDealQty(MConstants.INT_ZERO);
        order.setEntrustStatus(EntrustStatusEnum.REPORTED.name());
        return order;
    }
}
